<template>
  <div>
    <div class="upload">
      <el-alert
        :closable="false"
        :title="`支持jpg、jpeg、png格式，单次可最多选择${limit}张图片，每张不可大于${size}M，如果大于${size}M会自动为您过滤`"
        type="info"
      />
      <br>
      <el-upload
        ref="upload"
        :action="action"
        :auto-upload="false"
        :close-on-click-modal="false"
        :data="data"
        :file-list="fileList"
        :headers="headers"
        :limit="limit"
        :multiple="true"
        :name="name"
        :on-change="handleChange"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        accept="image/png, image/jpeg"
        class="upload-content"
        list-type="picture-card"
      >
        <i slot="trigger" class="el-icon-plus" />
        <el-dialog :visible.sync="dialogVisible" append-to-body title="查看大图">
          <div>
            <img :src="dialogImageUrl" alt="" width="100%">
          </div>
        </el-dialog>
      </el-upload>
    </div>
  </div>
</template>

<script>
import { baseUrl } from '@/config'
export default {
  name: 'ImageUpload',
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    name: {
      type: String,
      default: 'file'
    },
    limit: {
      type: Number,
      default: 50
    },
    size: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      action: `${baseUrl}/common/uploadfile`,
      headers: {},
      fileList: [],
      imgNum: 0,
      imgSuccessNum: 0,
      imgErrorNum: 0,
      dialogFormVisible: true,
      data: {}
    }
  },
  watch: {
    value(value) {
      this.fileList = value.map(v => { return { name: '产品图', url: v } })
    }
  },
  created() {
    this.fileList = this.value.map(v => { return { name: '', url: v } })
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleChange(file, fileList) {
      console.log('on-change', 'file:', file, 'fileList:', fileList)
      if (file.size > 1048576 * this.size) {
        fileList.map((item, index) => {
          if (item === file) {
            fileList.splice(index, 1)
          }
        })
        this.fileList = fileList
      } else {
        this.allImgNum = fileList.length
      }
      this.submitUpload()
    },
    handleSuccess(response, file, fileList) {
      console.log('on-success', 'response', response, 'file:', file, 'fileList:', fileList)
      if (!response.code) {
        this.imgNum = this.imgNum + 1
        this.imgSuccessNum = this.imgSuccessNum + 1
        this.$emit('input', fileList.map(v => {
          return v.url.startsWith('blob') ? v.response.data : v.url
        }))
        if (fileList.length === this.imgNum) {
          setTimeout(() => {
            this.$message.success(`上传完成! 共上传${fileList.length}张图片`)
          }, 1000)
        }
      }
    },
    // eslint-disable-next-line handle-callback-err
    handleError(err, file, fileList) {
      console.log('on-error', file, fileList)
      this.imgNum = this.imgNum + 1
      this.imgErrorNum = this.imgErrorNum + 1
      this.$message.error(`文件[${file.raw.name}]上传失败,文件大小为${Math.round(file.raw.size / 1024)}KB`)
    },
    handleRemove(file, fileList) {
      console.log('on-remove', 'file:', file, 'fileList:', fileList)
      this.$emit('input', fileList.map(v => {
        return v.url.startsWith('blob') ? v.response.data : v.url
      }))
      this.imgNum = this.imgNum - 1
      this.allNum = this.allNum - 1
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleExceed(files, fileList) {
      this.$message.error(`当前限制选择 ${this.limit} 个文件，本次选择了${files.length}个文件`)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload {
  .upload-content {
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }

    ::v-deep {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px 8px;
        border: 2px dashed #c0ccda;
      }

      .el-upload-list--picture {
        margin-bottom: 20px;
      }

      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px 8px;
        }
      }
    }
  }
}
</style>
